/**
 * localStorage缓存工具类
 * {
 *    _data: "",
 *    _expiration: date
 * }
 */

class Local {
   static instance;

   /**
    * 调用此静态方法实现单例
    * */
   static getInstance() {
      if (false === this.instance instanceof this) {
         this.instance = new this;
         // console.log("创建新对象");
      }
      return this.instance;
   }

   constructor() {
   }

   /**
    * 获取localStorage缓存
    * @param {string} key 缓存的key
    */
   get(key) {
      let value = localStorage.getItem(key);
      let dateTime = parseInt(new Date() / 1000);
      if (value === null) return null;
      try {
         value = JSON.parse(value);
         if (!value._expiration) return value._data || value;
         if (!value._data) return value;
         if (value._expiration < dateTime) return this.del(key);
         try {
            return JSON.parse(value._data);
         } catch (e) {
            return value._data;
         }
      } catch (e) {
         return value;
      }
   }

   /**
    * 设置localStorage缓存
    * @param {string} key 缓存的key
    * @param {object,string} value   存储的值
    * @param {number} expiration 过期时间以秒为单位(不传则没有过期时间)
    */
   set(key, value, expiration) {
      let localValue = "";
      if (expiration) {
         let _expiration = parseInt(new Date() / 1000) + expiration;   //过期时间
         localValue = JSON.stringify({
            _data: value,
            _expiration,
         });
      } else {
         if (typeof value == "object") {
            localValue = JSON.stringify(value);
         } else {
            localValue += "";
         }
      }
      localStorage.setItem(key, localValue);
   }

   /**
    * 删除localStorage缓存
    * @param {string} key 缓存的key
    */
   del(key) {
      key ? localStorage.removeItem(key) : localStorage.clear();
      return null;
   }
}

let local = Local.getInstance();

export default local;